#include "log_err.h"
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

typedef int (*vprintf_like_t)(const char *, va_list);
static vprintf_like_t s_log_print_func = &vprintf;

static char str[1024];
static void signway_log_writev(signway_log_level_t level,
                   const char *tag,
                   const char *format,
                   va_list args)
{
    /* 输出日志到终端 */
    (*s_log_print_func)(format, args);
    
    /* 输出日志到文件 */
    memset(str, 0, sizeof(str));
    snprintf(str, sizeof(str), format, args);
    //TODO
}

void signway_log_write(signway_log_level_t level,
                   const char *tag,
                   const char *format, ...)
{
    va_list list;
    va_start(list, format);
    signway_log_writev(level, tag, format, list);
    va_end(list);
}

/**
 * @return time stamp 时间戳
 */
uint32_t signway_log_timestamp(void)
{
    //CPU时间精确到1/CLOCKS_PER_SEC秒
    clock_t a = clock();
    return (a / 100) % 100000;
}

const char *signway_err_to_name(signway_err_t code)
{
    switch(code) {
    case SIGNWAY_ERR_NO_MEM:              return "Out of memory";
    case SIGNWAY_ERR_INVALID_ARG:         return "Invalid argument";
    case SIGNWAY_ERR_INVALID_STATE:       return "Invalid state";
    case SIGNWAY_ERR_INVALID_SIZE:        return "Invalid size";
    case SIGNWAY_ERR_NOT_FOUND:           return "Requested resource not found";
    case SIGNWAY_ERR_NOT_SUPPORTED:       return "Operation or feature not supported";
    case SIGNWAY_ERR_TIMEOUT:             return "Operation timed out";
    case SIGNWAY_ERR_INVALID_RESPONSE:    return "Received response was invalid";
    case SIGNWAY_ERR_INVALID_CRC:         return "CRC or checksum was invalid";
    case SIGNWAY_ERR_INVALID_VERSION:     return "Version was invalid";
    case SIGNWAY_ERR_INVALID_MAC:         return "MAC address was invalid";
    case SIGNWAY_ERR_NOT_INIT:            return "MAC address was invalid";
    case SIGNWAY_ERR_BUF:                 return "The buffer is too small";

    case SIGNWAY_ERR_MWIFI_BASE:          return "Starting number of MWIFI error codes";
    case SIGNWAY_ERR_MESPNOW_BASE:        return "Starting number of MESPNOW error codes";
    case SIGNWAY_ERR_MCONFIG_BASE:        return "Starting number of MCONFIG error codes";
    case SIGNWAY_ERR_MUPGRADE_BASE:       return "Starting number of MUPGRADE error codes";
    case SIGNWAY_ERR_MDEBUG_BASE:         return "Starting number of MDEBUG error codes";
    case SIGNWAY_ERR_MLINK_BASE:          return "Starting number of MLINK error codes";
    case SIGNWAY_ERR_CUSTOM_BASE:         return "Starting number of COUSTOM error codes";
    default :                             return "nothing find code";
    }
}
